<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <canvas style="border: 1px solid #ccc;" width="1000" height="800" id="mycanvas"></canvas>
</body>
<script>
    let canvas = document.getElementById('mycanvas')
    let ctx = canvas.getContext('2d')
    let colorList = ['#FD0', '#6C0', '#09F', '#F30', 'pink', 'skyblue', 'lime', 'orange', 'yellow']
    let ballList = new Array()
    //面向编程
    // 写法1
    class Ball {
            constructor(x, y, r, color) {
                this.x = x
                this.y = y
                this.r = r
                this.color = color
                this.dX = Math.random() * 10 - 5
                this.dY = Math.random() * 10 - 5
                this.dR = Math.random() * 0.5
                ballList.push(this)
            }
            update() {
                this.x += this.dX
                this.y += this.dY
                this.r -= this.dR
                if (this.r <= 0) {
                    ballList = ballList.filter(item => item !== this)
                }
            }
            render() {
                ctx.beginPath()
                ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false)
                ctx.fillStyle = this.color
                ctx.fill()
            }
        }
    // 写法2
    // function Ball(x, y, r, color) {
    //     this.x = x
    //     this.y = y
    //     this.r = r
    //     this.color = color
    //     this.dX = Math.random() * 10 - 5
    //     this.dY = Math.random() * 10 - 5
    //     this.dR = Math.random() * 0.5
    //     ballList.push(this)
    // }
    // Ball.prototype = {
    //     update: function () {
    //         this.x += this.dX
    //         this.y += this.dY
    //         this.r -= this.dR
    //         if (this.r <= 0) {
    //             ballList = ballList.filter(item => item !== this)
    //         }
    //     },
    //     render: function () {
    //         ctx.beginPath()
    //         ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false)
    //         ctx.fillStyle = this.color
    //         ctx.fill()
    //     }
    // }
    setInterval(() => {
        ctx.clearRect(0, 0, canvas.width, canvas.height)
        for (let i = 0; i < ballList.length; i++) {
            ballList[i].update()
            if (ballList[i]) {
                ballList[i].render()
            }
        }
    }, 20);
    canvas.addEventListener('mousemove', function (e) {
        new Ball(e.pageX, e.pageY, 25, colorList[Math.ceil(Math.random() * colorList.length)])
    })
</script>

</html>